package com.lxd.milktea.service.impl;

import com.lxd.milktea.dao.UserRepository;
import com.lxd.milktea.dataobject.User;
import com.lxd.milktea.enums.ResultEnum;
import com.lxd.milktea.enums.UserStatusEnum;
import com.lxd.milktea.exception.SellException;
import com.lxd.milktea.service.UserService;
import com.lxd.milktea.util.ResultVOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * @Author Ha
 * @DATE 2019/6/5 20:38
 **/
@Service
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;

    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public User findByUsernameAndPassword(String username, String password) {
            return userRepository.findByUserNameAndPassword(username, password);
    }

    @Override
    public User findByUsername(String username) {
        return userRepository.findByUserName(username);
    }

    @Override
    public User Login(String username, String password) throws SellException{
        User user = this.findByUsername(username);
        if(user==null){
            throw new SellException(ResultEnum.LOGIN_FAIL);
        }
        if(!DigestUtils.md5DigestAsHex((password+user.getSalt()).getBytes()).equals(user.getPassword())){
            throw new SellException(ResultEnum.LOGIN_FAIL);
        }
        return user;
    }

    @Override
    public Boolean register(User user) {
        //判断学生名字信息是否重复
        String userName = user.getUserName();
        User byUserName = userRepository.findByUserName(userName);
        if(byUserName!=null){
            return false;
        }
        String salt = UUID.randomUUID().toString().substring(0,5);
        user.setSalt(salt);
        user.setStatus(UserStatusEnum.NORMAL.getCode().byteValue());
        user.setPassword(DigestUtils.md5DigestAsHex((user.getPassword()+salt).getBytes()));
        return userRepository.save(user)!=null;
    }
}
